<template>
	<el-card>
		<el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="200px" @keyup.enter="handleDataForm()">
			<el-form-item :label="$t('profile.username')">
				<span>{{ store.userStore.user.username }}</span>
			</el-form-item>
			<el-form-item prop="old_strator_password" :label="$t('profile.oldPassword')">
				<el-input v-model="dataForm.old_strator_password" type="password"></el-input>
			</el-form-item>
			<el-form-item prop="new_strator_password" :label="$t('profile.newPassword')">
				<el-input v-model="dataForm.new_strator_password" type="password"></el-input>
			</el-form-item>
			<el-form-item prop="confirmPassword" :label="$t('profile.confirmPassword')">
				<el-input v-model="dataForm.confirmPassword" type="password"></el-input>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="handleDataForm" :loading="loading">{{ $t('confirm') }}</el-button>
			</el-form-item>
		</el-form>
	</el-card>
</template>

<script setup lang="ts" name="ProfilePassword">
import { ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import store from '@/store'
import { useI18n } from 'vue-i18n'
import { validatePassword } from '@/utils/validate'
import { updatePasswordApi } from '@/api/user'
import { ElMessage } from 'element-plus'
import { closeTab } from '@/utils/tabs'

const router = useRouter()
const route = useRoute()
const { t } = useI18n()
const dataFormRef: any = ref(null)
const loading = ref(false);

const dataForm = ref({
	old_strator_password: '',
	new_strator_password: '',
	confirmPassword: ''
})
const validatePassword2 = (rule: any, value: any, callback: (e?: Error) => any) => {
	if (value.length < 8) {
		callback(new Error('密码不能小于8位数'))
	} else if (dataForm.value.new_strator_password != dataForm.value.confirmPassword) {
		callback(new Error('两次输入密码不同'))
	} else {
		callback()
	}
}
const dataRules = ref({
	old_strator_password: [{ required: true, message: t('required'), trigger: 'blur' }],
	new_strator_password: [{ required: true, validator: validatePassword, trigger: 'blur' }],
	confirmPassword: [{ required: true, validator: validatePassword2, trigger: 'blur' }]
})

const handleDataForm = () => {
	dataFormRef.value.validate((valid: boolean) => {
		if (!valid) {
			return false
		}
        loading.value = true;
		// 修改密码
		updatePasswordApi({
            old_strator_password: dataForm.value.old_strator_password,
            new_strator_password: dataForm.value.new_strator_password,
        }).then(() => {
            loading.value = false;
			ElMessage.success('密码修改成功，请牢记新密码')
			// 关闭当前tab
			closeTab(router, route)
		}).catch(() => {
            loading.value = false;
        })
	})
}
</script>
